<!-- 路段管理 -->
<script setup lang="tsx">
import { reactive, ref, unref, watch } from 'vue'
import {
  highwayCityPageDataList,
  roadSystemDataList,
  highwayRoadPilePageDataList,
  highwayRoadPageDataList,
  highwayRoadSaveOrUpdate,
  highwayRoadDeleteById
} from '@/api/highway'
import { useTable } from '@/hooks/web/useTable'
import { Table } from '@/components/Table'
import { Delete } from '@element-plus/icons-vue'
import { BaseButton } from '@/components/Button'
import { ElButton } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search'
import { ContentWrap } from '@/components/ContentWrap'
import { Write, Detail } from './components'
import { geoOptions, gradeOptions, emergencyOptions } from '@/assets/data/trafficData'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import {
  querySearchAsync,
  handleSelect,
  setContentType,
  delCommonUsage
} from '@/utils/commonUsages'
import { useOtherStoreWithOut } from '@/store/modules/other'

const otherStore = useOtherStoreWithOut()

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await highwayRoadPageDataList(
      {
        pageNum: unref(currentPage),
        pageSize: unref(pageSize)
      },
      {
        ...unref(searchParams)
      }
    )
    return {
      list: res.data.records || [],
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await highwayRoadDeleteById({ id: unref(delId) })
    return !!res
  }
})

const { dataList, pageSize, currentPage, loading, total } = tableState
const { getList, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (data: any) => {
  currentPage.value = 1
  searchParams.value = data
  getList()
}

const delLoading = ref(false)
const delId = ref('')
const delData = async (row?: any) => {
  delId.value = row.id
  delLoading.value = true

  await delList(1).finally(() => {
    delLoading.value = false
  })
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const dialogWidth = ref('60%')
const dialogHeight = ref('auto')

const saveLoading = ref(false)
const writeRef = ref<ComponentRef<typeof Write>>()

const currentRow = ref()
const actionType = ref('')

const highwayCityList = ref([])
const RoadPileList = ref([])

const action = (row: any, type: string) => {
  dialogTitle.value = type
  actionType.value = type
  currentRow.value = {
    ...row,
    startPosV: row.startPos ? `${row.startPos?.longitude},${row.startPos?.latitude}` : '',
    endPosV: row.startPos ? `${row.endPos?.longitude},${row.endPos?.latitude}` : ''
  }
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = '新增'
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = '新增'
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    try {
      console.log('保存提交', formData)
      // 城市
      if (formData.cityId && highwayCityList.value.length > 0) {
        const cityInfo: any = highwayCityList.value.find((item: any) => item.id === formData.cityId)
        formData.city = cityInfo ? cityInfo.city : ''
      }
      // 桩号
      if (RoadPileList.value.length > 0) {
        if (formData.startPileId) {
          const info: any = RoadPileList.value.find((item: any) => item.id === formData.startPileId)
          formData.startPile = info ? info.pile : ''
        }
        if (formData.endPileId) {
          const info: any = RoadPileList.value.find((item: any) => item.id === formData.endPileId)
          formData.endPile = info ? info.pile : ''
        }
      }
      formData.projectId = otherStore.getProjectId || ''
      if (formData.startPosV) {
        const pos = formData.startPosV?.split(',')
        formData.startPos = {
          longitude: pos.length > 0 ? pos[0] : '',
          latitude: pos.length > 0 ? pos[1] : ''
        }
      }
      if (formData.endPosV) {
        const pos = formData.endPosV?.split(',')
        formData.startPos = {
          longitude: pos.length > 0 ? pos[0] : '',
          latitude: pos.length > 0 ? pos[1] : ''
        }
      }

      const res = await highwayRoadSaveOrUpdate(formData)
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: '序号',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'hwayNo',
    label: '高速公路编号',
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择高速公路编号',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: handleSelect,
          focus: () => {
            setContentType(2)
          }
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('hwayNo')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    }
  },
  {
    field: 'cityId',
    label: '所属地市',
    search: {
      component: 'Select',
      componentProps: {
        options: [],
        props: {
          label: 'city',
          value: 'id',
          key: 'id'
        },
        filterable: true,
        placeholder: '请选择所属地市',
        clearable: true
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        props: {
          label: 'city',
          value: 'id',
          key: 'id'
        },
        options: []
      }
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'city',
    label: '所属地市',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'roadType',
    label: '路段类型',
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择路段类型',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: handleSelect,
          focus: () => {
            setContentType(3)
          }
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('roadType')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    }
  },
  {
    field: 'roadName',
    label: '路段名称',
    search: {
      hidden: true
    }
  },
  {
    field: 'roadNo',
    label: '路段编码',
    search: {
      hidden: true
    }
  },
  {
    field: 'roadSystem',
    label: '所属路端系统',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        clearable: true,
        props: {
          label: 'systemName',
          value: 'systemNo',
          key: 'id'
        }
      },
      optionApi: async () => {
        const res = await roadSystemDataList()
        return res.data
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'grade',
    label: '公路等级',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: gradeOptions,

        clearable: true
      }
    }
  },
  {
    field: 'roadLen',
    label: '路段长度',
    search: {
      hidden: true
    }
  },
  {
    field: 'startPileId',
    label: '起始桩号',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [],
        props: {
          label: 'pile',
          value: 'id',
          key: 'id'
        },
        filterable: true,
        clearable: true
      }
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'startPile',
    label: '起始桩号',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'endPileId',
    label: '结束桩号',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [],
        props: {
          label: 'pile',
          value: 'id',
          key: 'id'
        },
        filterable: true,
        clearable: true
      }
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'endPile',
    label: '结束桩号',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'startPosV',
    label: '起始位置',
    form: {
      componentProps: {
        placeholder: '经度,纬度'
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'endPosV',
    label: '结束位置',
    form: {
      componentProps: {
        placeholder: '经度,纬度'
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'geo',
    label: '坐标系',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: geoOptions,
        clearable: true
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'emergency',
    label: '是否存在应急车道',
    search: {
      hidden: true
    },
    form: {
      component: 'RadioGroup',
      value: 0,
      componentProps: {
        options: emergencyOptions
      }
    },
    table: {
      slots: {
        default: ({ row }: any) => {
          return emergencyOptions.find((item) => item.value === row.emergency)?.label || ''
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          const value = data.emergency
          return <span>{emergencyOptions[value].label}</span>
        }
      }
    }
  },
  {
    field: 'lanes',
    label: '车道数',
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 2,
      componentProps: {
        min: 1
      }
    }
  },
  {
    field: 'sortOrder',
    label: '数据排序',
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 1,
      componentProps: {
        min: 0
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'lowSpeed',
    label: '设计时速（最低）',
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 80,
      componentProps: {
        min: 40,
        max: 140,
        step: 10
      }
    }
  },
  {
    field: 'highSpeed',
    label: '设计时速（最高）',
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 120,
      componentProps: {
        min: 40,
        max: 140,
        step: 10
      }
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'createUser',
    label: '创建人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'updateTime',
    label: '更新时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'updateUser',
    label: '修改人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 160,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <BaseButton type="primary" link onClick={() => action(row, '编辑')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" link onClick={() => action(row, '详情')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" link onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])
const { allSchemas } = useCrudSchemas(crudSchemas)

/** 获取所属城市列表 */
const getHighwayCityPageDataList = async () => {
  const res = await highwayCityPageDataList({ pageNum: 1, pageSize: 9999 }, {})
  if (!res || !res.data || !res.data.records) {
    return []
  }
  const searchNode = allSchemas.searchSchema.find((item) => item.field === 'cityId')
  const formNode = allSchemas.formSchema.find((item) => item.field === 'cityId')
  highwayCityList.value = res.data.records || []
  if (searchNode) {
    searchNode.componentProps.options = highwayCityList.value
  }
  if (formNode) {
    formNode.componentProps.options = highwayCityList.value
  }
}
/** 获取桩号列表 */
const getHighwayRoadPilePageDataList = async () => {
  const res = await highwayRoadPilePageDataList({ pageNum: 1, pageSize: 9999 }, {})
  if (!res || !res.data || !res.data.records) {
    return []
  }
  const node1 = allSchemas.formSchema.find((item) => item.field === 'startPileId')
  const node2 = allSchemas.formSchema.find((item) => item.field === 'endPileId')
  RoadPileList.value = res.data.records || []
  if (node1) {
    node1.componentProps.options = RoadPileList.value
  }
  if (node2) {
    node2.componentProps.options = RoadPileList.value
  }
}
getHighwayCityPageDataList()
getHighwayRoadPilePageDataList()
</script>
<template>
  <ContentWrap>
    <Search
      :schema="allSchemas.searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
      :operationAdd="true"
      @add="AddAction"
    />

    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :width="dialogWidth"
    :maxHeight="dialogHeight"
  >
    <Write
      v-if="['新增', '编辑'].includes(actionType)"
      ref="writeRef"
      :current-row="currentRow"
      :form-schema="allSchemas.formSchema"
    />
    <Detail
      v-if="actionType === '详情'"
      :current-row="currentRow"
      :detail-schema="allSchemas.detailSchema"
    />

    <template #footer>
      <BaseButton
        v-if="['新增', '编辑'].includes(actionType)"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        保存
      </BaseButton>

      <BaseButton @click="dialogVisible = false">关闭</BaseButton>
    </template>
  </Dialog>
</template>
<style scoped>
.w-130px {
  width: 130px;
}
</style>
